import config from '@/utils/config'
import socket from '@/utils/socket'
function getIndex (rooms, {index, name}) {
  return index === 'number' 
    ? index
    : rooms.findIndex( obj => obj.name == name)
}
export default {
  setName (state, payload) {
    state.x_name = payload
  },
  login(){
    let user = sessionStorage.getItem('user')
    if(user){
      socket.emit('push', {
        type: 'login',
        data: JSON.parse(user)
      })
    }
  },
  //添加房间
  roomsPush({ rooms }, { name }){
    if(config.ROOM_TOP < rooms.length) {
      if (rooms.some( obj => obj.name == name)){
        console.log('房间同名')
      } else {
        rooms.push({
          name,
          users: 0,
        })
      }
    } else {
      console.log('房间上限已满')
    }
  },
  //删除房间
  removeRomms({ rooms }, { index, name }){
    let i = getIndex(rooms, { index, name })
    rooms.splice(i, i + 1)
  },
  //房间名字
  setRoomName(state, name){
    state.roomName = name
  },
  //改变人数
  setUsers({ rooms }, {users, name, index }){
    rooms[getIndex(rooms, { index, name })].users = users
  }
}